<template>
  <div style="display: flex; justify-content: center; align-items: center">
    <div
      style="
        min-width: 900px;
        width: 900px;
        background-color: #fff;
        margin-top: 20px;
        padding: 20px;
        height: calc(100vh - 140px);
        overflow-y: auto;
      "
    >
      <div id="printBox" ref="pdfContent" v-loading="loading">
        <!-- 循环生成第几页 page-break为打印分页标识-->
        <!-- <div
          v-for="(pageItem, pageIndex) in printDataList"
          :key="pageItem?.id"
          class="page-break"
        > -->

        <div
          style="padding: 20px 0; margin: 0 10px; position: relative"
          ref="tableAll"
          id="table1"
        >
          <img
            src="@/assets/images/screen/jtlogo_sm.png"
            width="170"
            style="position: absolute; left: 10px; top: 5px"
          />
          <div
            style="
              font-size: 22px;
              display: flex;
              justify-content: center;
              margin-bottom: 5px;
            "
          >
            <div class="box1">
              <!-- <span>Dalian Giantech Automobile Parts Co., Ltd.</span> -->
              <span>材质检验报告</span>
              <span>Material Inspection Report</span>
            </div>
          </div>

          <!-- 送货单基本信息 -->
          <div
            style="
              display: flex;
              margin-bottom: 2px;
              font-size: 16px;
              font-weight: 400;
              color: #6e7073;
            "
          >
            <div style="flex: 1"></div>
            <div style="flex: 1">
              <div style="text-align: right">
                NO:{{ formData?.reportCode || "" }}
              </div>
            </div>
          </div>
          <table
            border="1"
            cellpadding="0"
            cellspacing="0"
            align="center"
            class="dashed-border"
          >
            <colgroup>
              <col width="60" />
              <col width="60" />
              <col width="60" />
              <col width="60" />
              <col width="60" />
              <col width="60" />

              <col width="60" />
              <col width="60" />
              <col width="60" />
              <col width="60" />
              <col width="60" />
              <col width="60" />
            </colgroup>
            <tbody>
              <tr>
                <td colspan="2">
                  <div class="box1">
                    <div>供应商</div>
                    <div>Supplier</div>
                  </div>
                </td>
                <td colspan="10">
                  <div class="box1">
                    <div style="font-size: 16px">
                      大连金泰汽车零部件有限公司
                    </div>
                    <div>Dalian Giantech Automobile Parts Company</div>
                  </div>
                </td>
              </tr>
              <tr>
                <td colspan="2">
                  <div class="box1">
                    <div>客户</div>
                    <div>Customer</div>
                  </div>
                </td>
                <td colspan="2">
                  {{ formData?.customerName || "" }}
                </td>
                <td colspan="2">
                  <div class="box1">
                    <div>品名</div>
                    <div>Part Name</div>
                  </div>
                </td>
                <td colspan="2">
                  {{ formData?.materialName || "" }}
                </td>
                <td colspan="2">
                  <div class="box1">
                    <div>品号</div>
                    <div>Part NO.</div>
                  </div>
                </td>
                <td colspan="2">
                  {{ formData?.materialCode || "" }}
                </td>
              </tr>

              <tr>
                <td colspan="2">
                  <div class="box1">
                    <div>批号</div>
                    <div>Lot/Batch</div>
                  </div>
                </td>
                <td colspan="2">
                  {{ formData?.materialBatch || "" }}
                </td>
                <td colspan="2">
                  <div class="box1">
                    <div>材质</div>
                    <div>Material</div>
                  </div>
                </td>
                <td colspan="2">
                  {{ formData?.materialQuality || "" }}
                </td>
                <td colspan="2">
                  <div class="box1">
                    <div>生产日期</div>
                    <div>Production Date</div>
                  </div>
                </td>
                <td colspan="2">
                  {{ formData?.approveDate || "" }}
                </td>
              </tr>
              <tr style="height: 180px">
                <td colspan="12"></td>
              </tr>
              <tr>
                <td colspan="1">
                  <div class="box1">
                    <div>编号</div>
                    <div>NO.</div>
                  </div>
                </td>
                <td colspan="3">
                  <div class="box1">
                    <div>检验项目</div>
                    <div>Test Item</div>
                  </div>
                </td>
                <td colspan="1">
                  <div class="box1">
                    <div>规格</div>
                    <div>Spec.</div>
                  </div>
                </td>
                <td colspan="3">
                  <div class="box1">
                    <div>方法</div>
                    <div>Method</div>
                  </div>
                </td>
                <td colspan="3">
                  <div class="box1">
                    <div>检验结果</div>
                    <div>Test Result(s)</div>
                  </div>
                </td>
                <td colspan="1" style="padding: 0">
                  <div class="box1">
                    <div>判定</div>
                    <div style="font-size: 11px">Judgement</div>
                  </div>
                </td>
              </tr>

              <template
                v-for="(group, groupName) in groupedData"
                :key="groupName"
              >
                <tr v-for="(row, rowIndex) in group.rows" :key="rowIndex">
                  <td>{{ row?.dataIndex || "" }}</td>
                  <td
                    :rowspan="group.rowspan"
                    v-if="rowIndex === 0"
                    colspan="3"
                  >
                    {{ row?.sopItemName || "" }}
                  </td>
                  <!-- <td>{{ row.sopItemStandard }}</td> -->
                  <td></td>
                  <td
                    colspan="3"
                    :rowspan="group.rowspan"
                    v-if="rowIndex === 0"
                  >
                    {{ row?.sopItemMethod || "" }}
                  </td>
                  <td
                    v-if="
                      row.sopItemPosition !== null && row.sopItemPosition !== ''
                    "
                    colspan="2"
                  >
                    <div>
                      {{ row.sopItemPosition || "" }}
                    </div>
                  </td>
                  <td :colspan="row.sopItemPosition ? 1 : 3">
                    <div>
                      {{ row.sopItemValue || "" }}
                    </div>
                  </td>
                  <td colspan="1">
                    <div>
                      {{
                        row.sopItemResult === "1"
                          ? "OK"
                          : row.sopItemResult === "0"
                          ? "NO"
                          : ""
                      }}
                    </div>
                  </td>
                </tr>
              </template>

              <tr v-if="groupedData.length === 0">
                <td colspan="12" style="height: 90px"></td>
              </tr>
              <!-- <tr>
                <td colspan="12">
                  {{ groupedData }}
                </td>
              </tr> -->
              <tr>
                <td colspan="12">
                  <div>
                    <span>金相图片metallograph</span>
                    <span style="margin-left: 15px">×100</span>
                    <span style="margin-left: 60px">硝酸浓度EtchedNital</span>
                    <span style="margin-left: 15px">5%</span>
                  </div>
                </td>
              </tr>
              <tr class="left">
                <td colspan="12">
                  <div
                    style="display: flex; flex-wrap: wrap; min-height: 110px"
                  >
                    <img
                      v-for="(item, index) in formData?.images"
                      :key="index"
                      :src="`${upPreviewUrl}${item.url}`"
                      style="
                        width: 100px;
                        height: 100px;
                        margin: 5px;
                        cursor: pointer;
                      "
                      @click="
                        handlePictureCardPreview(`${upPreviewUrl}${item.url}`)
                      "
                      alt=""
                    />
                  </div>
                </td>
              </tr>
              <tr>
                <td colspan="3">
                  <div class="box1">
                    <div>综合判定</div>
                    <div>ComprehensiveJudgement</div>
                  </div>
                </td>
                <td colspan="9">
                  {{
                    formData?.comprehensiveJudgment === "0"
                      ? "No"
                      : formData?.comprehensiveJudgment === "1"
                      ? "OK"
                      : ""
                  }}
                </td>
              </tr>
              <tr>
                <td colspan="3">
                  <div class="box1">
                    <div>检验人</div>
                    <div>Inspector</div>
                  </div>
                </td>
                <td colspan="3">
                  {{ formData?.inspector || "" }}
                </td>
                <td colspan="3">
                  <div class="box1">
                    <div>核准人</div>
                    <div>QC</div>
                  </div>
                </td>
                <td colspan="3">
                  {{ formData?.approveUserName || "" }}
                </td>
              </tr>
              <tr>
                <td colspan="3">
                  <div class="box1">
                    <div>检验日期</div>
                    <div>Date</div>
                  </div>
                </td>
                <td colspan="3">
                  {{ formData?.inspectDate || "" }}
                </td>
                <td colspan="3">
                  <div class="box1">
                    <div>核准日期</div>
                    <div>Date</div>
                  </div>
                </td>
                <td colspan="3">
                  {{ formData?.approveDate || "" }}
                </td>
              </tr>
            </tbody>
          </table>

          <!-- 信息提示区域 -->
        </div>
        <!-- </div> -->
      </div>
    </div>

    <div class="flex flex-col ml-3">
      <div>
        <el-button type="primary" @click="startPrint" class="mb-2 w-[96px]"
          >打 印</el-button
        >
      </div>

      <div>
        <el-button type="primary" @click="downloadPDF" class="mb-2 w-[96px]"
          >下载 PDF</el-button
        >
      </div>

      <div>
        <el-button @click="previewPDF" class="mb-2 w-[96px]"
          >预览 PDF</el-button
        >
      </div>
    </div>

    <el-dialog
      v-model="pdfPreviewDialog"
      title="PDF 预览"
      width="1100"
      :close-on-click-modal="false"
      draggable
      alignCenter
      class="printDialog"
    >
      <div style="height: 650px">
        <div v-if="pdfPreviewUrl" style="height: 650px">
          <embed
            :src="pdfPreviewUrl"
            type="application/pdf"
            style="width: 100%; height: 100%"
          />
        </div>
        <div v-else>正在生成预览，请稍候...</div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import html2pdfs from "html2pdf.js";
import printJS from "print-js";
import { mock } from "./index";
import { useRoute } from "vue-router";

const route = useRoute();

defineOptions({
  name: "QMSMATERIALINSPECTIONREPORT",
  inheritAttrs: false,
});

const loading = ref(false);

// 处理数据，计算 rowspan 和隐藏标志
// 计算分组后的数据
const groupedData = computed(() => {
  const result: any = {};
  const dataReal = JSON.parse(
    JSON.stringify(formData.value?.checkOrderDetails || [])
  );
  let dataRealIndex = 0;
  dataReal.forEach((item: any) => {
    if (!result[item.sopItemName]) {
      result[item.sopItemName] = {
        rowspan: 0,
        rows: [],
      };
    }
    dataRealIndex += 1;
    result[item.sopItemName].rows.push({
      dataRealIndex: dataRealIndex,
      sopItemName: item.sopItemName,
      sopItemStandard: item.sopItemStandard,
      sopItemMethod: item.sopItemMethod,
      sopItemPosition: item.sopItemPosition,
      sopItemValue: item.sopItemValue,
      sopItemResult: item.sopItemResult,
    });
    result[item.sopItemName].rowspan++;
  });

  // 转换为有序的对象数组
  const colRes = Object.entries(result).map(([name, info]) => ({
    name,
    ...info,
  }));

  let realIndex = 0;
  colRes?.forEach((resItem) => {
    resItem.rows?.forEach((rows: any) => {
      realIndex += 1;
      rows.dataIndex = realIndex;
    });
  });
  return colRes;
});

// 图片预览功能
const uploadApi = import.meta.env.VITE_APP_BASE_API;
const upPreviewUrl = `${uploadApi}/system/fileCenter/preview/`;
const handlePictureCardPreview = (url: string) => {
  url = url?.replace("fileCenter/download/", "fileCenter/preview/");
  window.open(url);
};

onMounted(() => {
  if (route.query.id) {
    getDetail();
  } else {
    formData.value = {};
  }
});
// 打印数据
const getDetail = async () => {
  loading.value = true;
  await request({
    url: `/qms/qmsreportrecord/report/query`,
    method: "get",
    params: {
      reportRecordId: route.query.id,
    },
  })
    .then((res) => {
      if (res.data != null) {
        formData.value = res.data;
        loading.value = false;
      } else {
        loading.value = false;
      }
    })
    .finally(() => {
      loading.value = false;
    });
};

// 开始打印
function startPrint() {
  // 开始打印
  setTimeout(() => {
    printJS({
      printable: "printBox", // 打印内容的容器 id
      type: "html", // 打印类型
      imageStyle: "width:100%;margin-bottom:20px;",
      scanStyles: false,
      style: `
      @media print {
        @page {
          margin: 8mm 5mm;
        }
        body {
          margin: 0;
        }
        .page-break {
          page-break-before: always;
        }
        .dashed-border {
          width: 100%;
          border-collapse: collapse; /* 使边框合并为单一边框 */
          border: 1px solid #333;
        }

        .dashed-border td,
        .dashed-border th {
          font-size: 14px;
          border: 1px solid #333;
          min-height: 30px;
          padding: 6px 7px;
          overflow-wrap: anywhere;
          line-height: 24px;
          word-break: break-all;
        }

        tr {
          page-break-inside: avoid;
        }

        .bold td {
          font-weight: 600;
          text-align: center;
        }

        td {
          text-align: center;
        }

        .left td {
          text-align: left;
        }

        .box1 {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }

        .box1 div:nth-child(1) {
          font-size: 14px;
        }
        .box1 div:nth-child(2) {
          line-height: 20px;
          font-size: 13px;
        }
      }
    `,
    });
  }, 1000);
}

// 模拟数据
// const formData = ref(mock.data);
const formData = ref<any>({});

const pdfContent = ref(null);
const pdfPreviewDialog = ref(false);
const pdfPreviewUrl = ref<any>(null);

const pdfOptions = {
  filename: formData.value?.reportCode
    ? `材质检验报告(${formData.value?.reportCode})`
    : `材质检验报告.pdf`, // 指定生成文件的名称
  margin: [8, 5],
  image: { type: "jpeg", quality: 1 },
  html2canvas: { scale: 2, useCORS: true, logging: false },
  jsPDF: { unit: "mm", format: "a4", orientation: "portrait" },
  splitTextToRows: false, // 关闭文本拆分行
};
const previewPDF = () => {
  const element = pdfContent.value;

  if (!element) {
    console.error("Error: pdfContent is not defined or not bound to the DOM.");
    return;
  }

  const container = document.getElementById("printBox");
  if (!container) {
    console.error("Error: #pdf-content element not found in the DOM.");
    return;
  }

  container.classList.add("export");

  pdfPreviewDialog.value = true;
  pdfPreviewUrl.value = null;

  html2pdfs()
    .from(element)
    .set(pdfOptions)
    .toPdf()
    .get("pdf")
    .then((pdf: any) => {
      const pdfBlob = pdf.output("blob");
      pdfPreviewUrl.value = URL.createObjectURL(pdfBlob);
    })
    .finally(() => {
      container.classList.remove("export");
    });
};

const downloadPDF = () => {
  const element = pdfContent.value;
  html2pdfs().set(pdfOptions).from(element).save();
};
</script>

<style lang="scss" scoped>
.app-container {
  height: inherit;
  overflow: scroll;
  padding: 0;
}

:deep(.printDialog .el-dialog__body) {
  padding: 10px !important;
  height: calc(100vh - 220px);
  overflow: scroll;
}

// table {
//   page-break-inside: avoid;
// }

// table + table {
//   page-break-before: always;
// }

.dashed-border {
  width: 100%;
  border-collapse: collapse; /* 使边框合并为单一边框 */
  border: 1px solid #606266;
}

.dashed-border td,
.dashed-border th {
  color: #6e7073;
  font-size: 14px;
  border: 1px solid #606266;
  min-height: 30px;
  padding: 6px 7px;
  overflow-wrap: anywhere;
  line-height: 24px;
  word-break: break-all;
}

.page-break {
  page-break-before: always;
}

tr {
  page-break-inside: avoid;
}

.bold td {
  font-weight: 600;
  text-align: center;
}

td {
  text-align: center;
}

.left td {
  text-align: left;
}

.box1 {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.box1 div:nth-child(1) {
  font-size: 14px;
}
.box1 div:nth-child(2) {
  line-height: 20px;
  font-size: 13px;
}
</style>
